<template>
  <div class="flight-booking">
    <el-card class="booking-card">
      <div slot="header" class="clearfix">
        <span>机票预订</span>
      </div>

      <!-- 航班信息展示 -->
      <el-descriptions title="航班信息" :column="2" border>
        <el-descriptions-item label="航班号">{{ flight.flightNumber }}</el-descriptions-item>
        <el-descriptions-item label="航线">{{ flight.departureCity }} - {{ flight.arrivalCity }}</el-descriptions-item>
        <el-descriptions-item label="起飞时间">{{ formatDateTime(flight.departureTime) }}</el-descriptions-item>
        <el-descriptions-item label="到达时间">{{ formatDateTime(flight.arrivalTime) }}</el-descriptions-item>
        <el-descriptions-item label="飞行时长">{{ flight.flightDuration }}</el-descriptions-item>
        <el-descriptions-item label="机型">{{ flight.aircraftType }}</el-descriptions-item>
      </el-descriptions>

      <!-- 选择机票类型和数量 -->
      <el-form :model="bookingForm" :rules="rules" ref="bookingForm" label-width="100px" class="booking-form">
        <el-form-item label="机票类型" prop="ticketType">
          <el-radio-group v-model="bookingForm.ticketType">
            <el-radio-button v-for="ticket in tickets" 
                           :key="ticket.ticketType" 
                           :label="ticket.ticketType"
                           :disabled="ticket.seatAvailability <= 0">
              {{ ticket.ticketType }} (¥{{ ticket.price }})
              <span class="seat-info">(剩余: {{ ticket.seatAvailability }})</span>
            </el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="购票数量" prop="quantity">
          <el-input-number 
            v-model="bookingForm.quantity" 
            :min="1" 
            :max="getMaxTickets()"
            :disabled="!bookingForm.ticketType">
          </el-input-number>
        </el-form-item>

        <el-form-item label="总价">
          <span class="total-price">¥{{ calculateTotal() }}</span>
        </el-form-item>

        <!-- 乘客信息 -->
        <el-form-item label="乘客信息" required>
          <div v-for="(passenger, index) in bookingForm.passengers" :key="index" class="passenger-info">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item
                  :prop="'passengers.' + index + '.name'"
                  :rules="rules.passengerName"
                >
                  <el-input v-model="passenger.name" placeholder="姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  :prop="'passengers.' + index + '.idCard'"
                  :rules="rules.idCard"
                >
                  <el-input v-model="passenger.idCard" placeholder="身份证号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  :prop="'passengers.' + index + '.phone'"
                  :rules="rules.phone"
                >
                  <el-input v-model="passenger.phone" placeholder="手机号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="2" v-if="index > 0">
                <el-button type="danger" icon="el-icon-delete" circle @click="removePassenger(index)"></el-button>
              </el-col>
            </el-row>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitBooking">提交订单</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'

export default {
  name: 'FlightBooking',
  data() {
    return {
      flight: {},
      tickets: [],
      bookingForm: {
        ticketType: '',
        quantity: 1,
        passengers: [{
          name: '',
          idCard: '',
          phone: ''
        }]
      },
      rules: {
        ticketType: [
          { required: true, message: '请选择机票类型', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请选择购票数量', trigger: 'change' }
        ],
        passengerName: [
          { required: true, message: '请输入乘客姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'bookingForm.quantity'(newVal) {
      // 当数量变化时，调整乘客信息表单数量
      const diff = newVal - this.bookingForm.passengers.length
      if (diff > 0) {
        for (let i = 0; i < diff; i++) {
          this.bookingForm.passengers.push({
            name: '',
            idCard: '',
            phone: ''
          })
        }
      } else if (diff < 0) {
        this.bookingForm.passengers.splice(newVal)
      }
    }
  },
  created() {
    this.fetchFlightDetails()
    this.fetchTickets()
  },
  methods: {
    async fetchFlightDetails() {
      try {
        const response = await axios.get(`/flights/${this.$route.params.id}`)
        if (response.data.code === 0) {
          this.flight = response.data.data
        } else {
          this.$message.error(response.data.msg || '获取航班信息失败')
        }
      } catch (error) {
        this.$message.error('网络错误，请稍后重试')
        console.error('Error fetching flight details:', error)
      }
    },
    async fetchTickets() {
      try {
        const response = await axios.get(`/flights/${this.$route.params.id}/tickets`)
        if (response.data.code === 0) {
          this.tickets = response.data.data
        } else {
          this.$message.error(response.data.msg || '获取机票信息失败')
        }
      } catch (error) {
        this.$message.error('网络错误，请稍后重试')
        console.error('Error fetching tickets:', error)
      }
    },
    getMaxTickets() {
      if (!this.bookingForm.ticketType) return 0
      const selectedTicket = this.tickets.find(t => t.ticketType === this.bookingForm.ticketType)
      return selectedTicket ? selectedTicket.seatAvailability : 0
    },
    calculateTotal() {
      if (!this.bookingForm.ticketType || !this.bookingForm.quantity) return 0
      const selectedTicket = this.tickets.find(t => t.ticketType === this.bookingForm.ticketType)
      return selectedTicket ? selectedTicket.price * this.bookingForm.quantity : 0
    },
    removePassenger(index) {
      this.bookingForm.passengers.splice(index, 1)
      this.bookingForm.quantity = this.bookingForm.passengers.length
    },
    formatDateTime(datetime) {
      return moment(datetime).format('YYYY-MM-DD HH:mm')
    },
    async submitBooking() {
      try {
        await this.$refs.bookingForm.validate()
        
        const response = await axios.post('/orders', {
          flightId: this.$route.params.id,
          ticketType: this.bookingForm.ticketType,
          quantity: this.bookingForm.quantity,
          passengers: this.bookingForm.passengers
        })

        if (response.data.code === 0) {
          this.$message.success('订单提交成功')
          this.$router.push({
            name: 'OrderDetail',
            params: { id: response.data.data.orderId }
          })
        } else {
          this.$message.error(response.data.msg || '订单提交失败')
        }
      } catch (error) {
        if (error.name === 'ValidationError') {
          this.$message.warning('请完善表单信息')
        } else {
          this.$message.error('网络错误，请稍后重试')
          console.error('Error submitting booking:', error)
        }
      }
    },
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.flight-booking {
  padding: 20px;
}

.booking-card {
  margin-bottom: 20px;
}

.booking-form {
  margin-top: 20px;
}

.passenger-info {
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.total-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.seat-info {
  font-size: 12px;
  color: #909399;
  margin-left: 5px;
}

.el-radio-button {
  margin-right: 10px;
}
</style> 